<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="si" placeholder="请选择分类" size="small">
              <el-option
                v-for="item in CateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="sz" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="shai"
              >筛选</el-button
            >
            <el-button type="info" size="small" @click="chongzhi"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="published"
          >发表文章</el-button
        >
      </div>

      <!-- 文章列表 -->
      <el-table :data="artList" style="width: 100%">
        <el-table-column label="文章标题" width="180">
          <template v-slot="scope">
            <el-link @click="xian(scope.row.id)" type="primary">{{
              scope.row.title
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="分类" width="180">
        </el-table-column>
        <el-table-column label="发布时间">
          <template v-slot="scope">
            {{ formatData(scope.row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="180">
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template v-slot="scope">
            <el-button size="mini" type="danger" @click="shanchu(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 弹框 -->
      <el-dialog
        @closed="pub"
        fullscreen
        title="发表文章"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <!-- 弹框内容 -->
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="ruleForm.title"> </el-input>
          </el-form-item>
          <el-form-item label="文章分类" prop="cate_id">
            <el-select
              @change="$refs.ruleForm.clearValidate('cate_id')"
              v-model="ruleForm.cate_id"
              placeholder="请选择活动区域"
            >
              <template v-for="item in CateList">
                <el-option
                  :label="item.cate_name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item label="文章内容" prop="content">
            <quill-editor
              @change="$refs.ruleForm.clearValidate('content')"
              v-model="ruleForm.content"
            >
            </quill-editor>
          </el-form-item>
          <el-form-item label="文章封面" prop="cover_img">
            <!-- 用来显示封面的图片 -->
            <img
              v-if="ruleForm.cover_img"
              :src="ruleForm.cover_img"
              alt=""
              class="cover-img"
              ref="imgRef"
            />
            <img
              v-else
              src="../../../assets/images/cover.jpg"
              alt=""
              class="cover-img"
              ref="imgRef"
            />
            <br />
            <!-- 文件选择框，默认被隐藏 -->
            <input
              v-if="dialogVisible"
              @change="Uploadthepicture"
              type="file"
              style="display: none"
              accept="image/*"
              ref="iptFile"
            />
            <!-- 选择封面的按钮 -->
            <el-button type="text" @click="$refs.iptFile.click()"
              >+ 选择封面</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('已发布')"
              >发布</el-button
            >
            <el-button type="info" @click="submitForm('草稿')"
              >存为草稿</el-button
            >
          </el-form-item>
        </el-form>
      </el-dialog>
      <!--  -->
      <!-- 文章表格区域 -->
    </el-card>
    <!-- 详情表格 -->
    <!-- 查看文章详情的对话框 -->
    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="Visible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ formatData(artDetail.pub_date) }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <img
        :src="'http://www.liulongbin.top:3008' + artDetail.cover_img"
        alt=""
      />

      <div v-html="artDetail.content"></div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  created () {
    this.getArtCate()
    this.getartList()
  },
  data () {
    return {
      artDetail: {},
      Visible: false,
      si: '',
      sz: '',
      total: 0,
      artList: [],
      dialogVisible: false,
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      CateList: [],
      ruleForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: null,
        state: ''
      },
      ql: null,
      bl: null,
      // 表单校验
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '文章标题的长度为1-30个字符',
            trigger: 'blur'
          }
        ],
        cate_id: [
          { required: true, message: '请选择文章分类', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '文本框不能为空', trigger: 'blur' }
        ],
        cover_img: [
          { required: true, message: '未选择文章封面', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 删除
    shanchu (id) {
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http
            .delete('/my/article/info', { params: { id } })
            .then(({ data: res }) => {
              if (res.code === 0) {
                this.$message({
                  type: 'success',
                  message: res.message
                })
                // this.getartList()
                if (this.artList.length === 1 && this.q.pagenum > 1) {
                  this.q.pagenum--
                }
                this.getartList()
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 详情
    xian (id) {
      this.Visible = true
      this.$http
        .get('/my/article/info', { params: { id } })
        .then(({ data: res }) => {
          if (res.code === 0) {
            this.artDetail = res.data
          }
        })
    },
    // 筛选
    shai () {
      this.q.pagenum = 1
      this.q.cate_id = this.si
      this.q.state = this.sz
      this.getartList()
    },

    // 重置
    chongzhi () {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.getartList()
    },
    // 页面长度一页面显示多少行
    handleSizeChange (size) {
      this.q.pagesize = size
      this.getartList()
    },
    // 页面改动时候拿数据
    handleCurrentChange (cur) {
      this.q.pagenum = cur
      this.getartList()
    },
    // 格式化时间
    formatData (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss ')
    },
    // 获取文章列表数据
    getartList () {
      this.$http
        .get('/my/article/list', {
          params: this.q
        })
        .then(({ data: res }) => {
          console.log(res)
          this.total = res.total
          if (res.code === 0) {
            this.artList = res.data
          }
        })
    },
    pub () {
      this.$refs.ruleForm.resetFields()
    },
    // 选择头像
    Uploadthepicture (e) {
      if (e.target.files.length === 0) {
        return (this.ruleForm.cover_img = null)
      }
      // 实例化一个转换成base64
      const fr = new FileReader()
      // 转换
      this.bl = e.target.files[0]
      fr.readAsDataURL(e.target.files[0])
      fr.onload = (e) => {
        // 赋值给data里面的数据
        this.ruleForm.cover_img = e.target.result
        this.$refs.ruleForm.clearValidate('cover_img')
      }
    },
    handleClose (done) {
      this.$confirm('确认关闭当前页面数据会丢失的哦？', '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then((_) => {
          done()
          console.log(111)
        })
        .catch((_) => {
          console.log(22)
        })
    },
    published () {
      this.dialogVisible = true
    },
    // 获取文章分类
    async getArtCate () {
      const { data: res } = await this.$http.get('/my/cate/list')
      //  获取成功赋值给data里面的数据
      if (res.code === 0) {
        this.CateList = res.data
      }
    },
    // 发布
    submitForm (stat) {
      this.ruleForm.state = stat
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // console.log(this.ruleForm.cover_img)
          //
          this.ql = this.ruleForm.cover_img
          this.ruleForm.cover_img = this.bl
          //

          const fr = new FormData()
          for (const key in this.ruleForm) {
            fr.append(key, this.ruleForm[key])
          }
          this.$http.post('/my/article/add', fr).then(({ data: res }) => {
            if (res.code === 0) {
              this.$message({
                message: res.message,
                type: 'success'
              })
              // 关闭页面
              this.dialogVisible = false
              this.getartList()
            }
          })
          this.ruleForm.cover_img = this.ql
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
  .el-select {
    width: 100%;
  }
}
.el-select {
  width: 100%;
}
/deep/.ql-editor {
  min-height: 300px;
}
.cover-img {
  width: 400px;
  height: 400px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
</style>
